<!-- 采购合同详情 -->
<template>
  <div class="registerDetail">
    <van-nav-bar :title="$route.meta.title" left-text="返回" left-arrow :fixed="true" :placeholder="true" @click-left="$router.go(-1)" :right-text="auditBtn" @click-right="editApply()" />
    <div>
      <div class="headerbox">
        <div class="header_top" v-if="billidColumns && billidColumns.length >= 0">
          <div class="header_item" v-for="(item, index) in billidColumns" :key="index" @click="handleClick(index)" :class="tabIndex == index ? 'active' : ''">
            <div class="txt">{{ item.number }}</div>
            <div class="txt1">{{ item.bizDate }}</div>
          </div>
        </div>
      </div>
    </div>
    <van-swipe class="my-swipe" :autoplay="3000" indicator-color="white">
      <van-swipe-item v-for="(item, index) in dataSource.imageCol" :key="index">
        <img :src="item.imageUrl" />
      </van-swipe-item>
    </van-swipe>
    <div class="buy_content">
      <div class="carInfo">
        <div class="buy_name">{{ dataSource.SHCarModel }}</div>
        <div class="carInfo_No flex">
          <div class="carInfo_No_item">{{ dataSource.carNo }}</div>
          <div class="carInfo_No_item">{{ dataSource.vinCode }}</div>
        </div>
        <div class="carInfo_item">销售合同编号：{{ dataSource.billNumber }}</div>
        <div class="carInfo_item">销售合同状态：{{ dataSource.billStatus }}</div>
        <div class="carInfo_item">签约日期：{{ dataSource.bizDate }}</div>
        <div class="carInfo_item">品牌：{{ dataSource.brand }}</div>
        <div class="carInfo_item">展厅：{{ dataSource.showOrgName }}</div>
        <div class="carInfo_item">签约公司：{{ dataSource.signCompany }}</div>
        <div class="carInfo_item">销售类型：{{ dataSource.saleTypes }}</div>
        <div class="carInfo_item">二手车销售类型：{{ dataSource.SHCarSaleType }}</div>
        <div class="carInfo_item">受买人（乙方）{{ dataSource.buyer }}</div>
        <div class="carInfo_item">备注：{{ dataSource.note }}</div>
      </div>
      <div class="carInfo">
        <!-- <div class="carInfo_title">签约信息</div> -->
        <div class="carInfo_item">合同总价：{{ dataSource.tatalSaleAmt }}</div>
        <div class="carInfo_item">车辆实际售价：{{ dataSource.carSalePrice }}</div>
        <div class="carInfo_item">累计收款金额：{{ dataSource.totalReceAmount }}</div>
        <div class="carInfo_item">整车开票金额：{{ dataSource.commitAmount }}</div>
        <div class="carInfo_item flex">
          <div class="carInfo_item_price">精品售价：{{ dataSource.qualityPrice }}</div>
          <div class="carInfo_item_price">精品限价：{{ dataSource.qualityPriceLimit }}</div>
        </div>
        <div class="carInfo_item flex">
          <div class="carInfo_item_price">是否付全款：{{ dataSource.isReceived ? "是" : "否" }}</div>

          <div class="carInfo_item_price">是否开全票：{{ dataSource.isCommit ? "是" : "否" }}</div>
        </div>
        <div class="carInfo_item">最后收款日期：{{ dataSource.lastRecAmountDate }}</div>
        <div class="carInfo_item">整车开票日期：{{ dataSource.invoiceDate }}</div>
        <div class="carInfo_item flex">
          <div class="carInfo_item_price">是否保险：{{ dataSource.isInsur ? "是" : "否" }}</div>
          <div class="carInfo_item_price">未售精品：{{ dataSource.isNotSalePart ? "是" : "否" }}</div>
        </div>
        <div class="carInfo_item flex">
          <div class="carInfo_item_price">出库状态：{{ dataSource.stocked }}</div>
          <div class="carInfo_item_price">出库日期：{{ dataSource.stockDate }}</div>
        </div>
      </div>
    </div>
    <div class="buy_footer flex">
      <div class="buy_footer_item flex" @click="handleFile">
        <div class="buy_footer_lt">
          <div>销售合同附件</div>
          <div class="txt">点击查看</div>
        </div>
        <div class="buy_footer_rt">
          <van-icon name="arrow" />
        </div>
      </div>
      <div class="buy_footer_item flex" @click="
          getDestInfoBySourceIdAndDestBosType(
            'E6265F39',
            dataSource.isGenReceive
          )
        ">
        <div class="buy_footer_lt">
          <div>整车收款单</div>
          <div class="txt">{{ dataSource.isGenReceive ? "点击查看" : "未生成" }}</div>
        </div>
        <div class="buy_footer_rt">
          <van-icon name="arrow" />
        </div>
      </div>
      <div class="buy_footer_item flex" @click="
          getDestInfoBySourceIdAndDestBosType(
            '352AA2EE',
            dataSource.isGenInvoice
          )
        ">
        <div class="buy_footer_lt">
          <div>整车开票单</div>
          <div class="txt">{{ dataSource.isGenInvoice ? "点击查看" : "未生成" }}</div>
        </div>
        <div class="buy_footer_rt">
          <van-icon name="arrow" />
        </div>
      </div>
      <div class="buy_footer_item flex" @click="
          getDestInfoBySourceIdAndDestBosType(
            '256737DC',
            dataSource.isGenSaleIssue
          )
        ">
        <div class="buy_footer_lt">
          <div>销售出库单</div>
          <div class="txt">{{ dataSource.isGenSaleIssue ? "点击查看" : "未生成" }}</div>
        </div>
        <div class="buy_footer_rt">
          <van-icon name="arrow" />
        </div>
      </div>
      <div class="buy_footer_item flex" @click="
          getDestInfoBySourceIdAndDestBosType(
            'F6F82555',
            dataSource.isGenBillInsure
          )
        ">
        <div class="buy_footer_lt">
          <div>保险登记单</div>
          <div class="txt">{{ dataSource.isGenBillInsure ? "点击查看" : "未生成" }}</div>
        </div>
        <div class="buy_footer_rt">
          <van-icon name="arrow" />
        </div>
      </div>
      <div class="buy_footer_item flex" @click="
          getDestInfoBySourceIdAndDestBosType(
            'B613A119',
            dataSource.isGenConsignAgreement
          )
        ">
        <div class="buy_footer_lt">
          <div>代办委托书</div>
          <div class="txt">{{ dataSource.isGenConsignAgreement ? "点击查看" : "未生成" }}</div>
        </div>
        <div class="buy_footer_rt">
          <van-icon name="arrow" />
        </div>
      </div>
      <div class="buy_footer_item flex" @click="
          getDestInfoBySourceIdAndDestBosType(
            'DFC3B640',
            dataSource.isGenAuditCreditFee
          )
        ">
        <div class="buy_footer_lt">
          <div>金融服务费收款</div>
          <div class="txt">{{ dataSource.isGenAuditCreditFee ? "点击查看" : "未生成" }}</div>
        </div>
        <div class="buy_footer_rt">
          <van-icon name="arrow" />
        </div>
      </div>
    </div>

    <van-popup v-model="updateServiceVisible" position="bottom">
      <van-picker show-toolbar title="请选择单据" :columns="columns" @confirm="handleSelectConfirm" @cancel="updateServiceVisible = false" value-key="text" />
    </van-popup>
    <!-- 操作面板 -->
    <van-share-sheet v-model="showShare" :options="options" @select="onSelect" />
    <div class="morebox">
      <div class="moreBtn" @click="handleShowDo">更多操作</div>
    </div>
    <!-- 审核情况 -->
    <AuditRecord :visible="auditVisible" :billId="dataSource.billId ? dataSource.billId : detailId" @close="auditVisible = false"></AuditRecord>
  </div>
</template>

<script>
import {
  Empty,
  Field,
  Form,
  ImagePreview,
  ShareSheet,
  Dialog,
  Swipe,
  SwipeItem,
  Notify
} from "vant";
import { getCookies } from "@/utils/util.js";
import icon_edit from "@/assets/images/icon_edit.png";
import sellManageApi from "@/api/sellManageApi";
import AuditRecord from "@/components/AuditRecord";
import white_png from "@/assets/images/white.png";

export default {
  name: "buyContractDetail",
  components: {
    Empty,
    Field,
    Form,
    ImagePreview,
    ShareSheet,
    Dialog,
    Swipe,
    SwipeItem,
    AuditRecord,
    Notify
  },
  data() {
    return {
      showTimerPicker: false,
      dataSource: {
        billId: "", //单据Id
        billNumber: "", //委托单编号
        bizDate: "", //业务日期
        billStatus: "", //单据状态
        brand: "", //所属品牌
        showOrgName: "", //所属展厅
        signCompany: "", //签约公司
        signCompanyId: "", //签约公司
        SHCarSaleType: "", //二手车销售类型
        buyer: "", //乙方买受人
        note: "", //备注
        totalRecvAmt: "", //合同总价
        totalRecvRate: "", //车辆实际售价
        qualityPrice: "", //精品售价
        qualityPriceLimit: "", //精品限价
        isNotSalePart: "", //未售精品
        SHCarModel: "", //二手车车型
        carNo: "", //车牌号
        totalReceAmount: "", //累计收款金额
        commitAmount: "", //整车开票金额
        isReceived: "", //是否收全款
        lastReceAmountDate: "", //最后首款日期
        isCommit: "", //是否开票
        invoiceDate: "", //整车开票日期
        isInsur: "", //是否保险
        stocked: "", //出库状态
        stockDate: "", //出库日期
        saleTypes: "", //销售类型
        isAllcoated: "", //是否配对
        isCanout: "", //可出库
        isCanInvoice: "", //可开票
        payAmount: "" //应付金额
      },
      uploader: [],
      columns: [],
      desBosType: "",
      showSelectPicker: false,
      disabled: false,
      detailId: "",
      tabActive: 0,
      userId: getCookies("userId"), //用户ID，必填，String
      showShare: false,
      options: [
        [
          { name: "生成销售出库", icon: icon_edit, value: 1 },
          { name: "", icon: white_png, value: 98 },
          { name: "", icon: white_png, value: 99 }
        ]
      ],
      billidColumns: [], // 单据列表ID
      tabIndex: 0,
      updateServiceVisible: false,
      updateServiceData: {
        fixCenterId: "",
        fixCenterName: "",
        currentServerPsnName: "",
        serverPsnName: "",
        serverPsnId: "",
        id: "",
        userId: ""
      },
      auditBtn: "",
      auditVisible: false
    };
  },

  mounted() {
    if (this.$route.query) {
      this.detailId = this.$route.query.billId;
      this.getDetail(this.detailId);
    }
    if (this.$route.query && this.$route.query.list) {
      this.billidColumns = this.$route.query.list;
    }
  },
  methods: {
    handleClick(index) {
      this.tabIndex = index;
      let billId = this.billidColumns[index].billId;
      this.detailId = billId;
      this.getDetail(this.detailId);
    },
    handleSelectConfirm(data) {
      switch (this.desBosType) {
        case "E6265F39":
          // 整车收款单
          this.$router.push({
            path: "/salesManageSaleReceive",
            query: {
              billId: data.billId,
              orderId: this.dataSource.billId,
              desBosType: "E6265F39"
            }
          });
          break;
        case "352AA2EE":
          // 整车开票单
          this.$router.push({
            path: "/salesManageSaleInvoice",
            query: {
              billId: data.billId,
              orderId: this.dataSource.billId,
              desBosType: "352AA2EE"
            }
          });
          break;
        case "256737DC":
          // 销售出库单
          this.$router.push({
            path: "/salesManageSaleIssued",
            query: {
              billId: data.billId,
              orderId: this.dataSource.billId,
              desBosType: "256737DC"
            }
          });

          break;
        case "F6F82555":
          // 保险登记单
          this.$router.push({
            path: "/salesManageInsurance",
            query: {
              billId: data.billId,
              orderId: this.dataSource.billId,
              desBosType: "F6F82555"
            }
          });
          break;
        case "B613A119":
          // 代办委托书
          this.$router.push({
            path: "/salesManageDoTrust",
            query: {
              billId: data.billId,
              orderId: this.dataSource.billId,
              desBosType: "B613A119"
            }
          });

          break;
        case "DFC3B640":
          // 金融服务费收款单
          this.$router.push({
            path: "/salesManageFinalService",
            query: {
              billId: data.billId,
              orderId: this.dataSource.billId,
              desBosType: "DFC3B640"
            }
          });

          break;

        default:
          break;
      }
    },
    // 格式化单据结果
    reduceRes(data) {
      let list = [];
      data.forEach(element => {
        list.push({
          text: "单号:" + element.number + " ; 日期:" + element.bizDate,
          billId: element.billId
        });
      });
      return list;
    },
    // 根据类型ID获取单据列表
    getDestInfoBySourceIdAndDestBosType(desBosType, state) {
      if (!state) {
        this.$toast.fail("无下游单据");
        return;
      }
      this.desBosType = desBosType;
      sellManageApi
        .secondHandCarFacade({
          method: "getDestInfoBySourceIdAndDestBosType", //固定值
          userId: "", //用户ID，必填，String
          orgId: "", //登录组织Id，必填，String
          billId: this.dataSource.billId, //单据Id，必填，String
          desBosType: desBosType
        })
        .then(res => {
          if (res.code == 1) {
            if (res.data.length >= 1) {
              this.columns = this.reduceRes(res.data);
              this.handleSelectConfirm(res.data[0]);
            } else {
              this.$toast.fail("无下游单据");
            }
          } else {
            this.$toast.fail("无下游单据");
          }
        });
    },
    getDetail(billId) {
      sellManageApi
        .secondHandCarFacade({
          method: "getSaleContractById", //固定值
          userId: "", //用户ID，必填，String
          orgId: "", //登录组织Id，必填，String
          billId: billId //单据Id，必填，String
        })
        .then(res => {
          if (res.code == 1) {
            this.dataSource = res.data;
            if (this.dataSource.billStatus != "保存") {
              this.auditBtn = "审批情况";
            }
          }
        });
    },

    // 选择下拉
    handleSelect(field) {
      if (this.disabled) {
        return;
      }
      this.showSelectPicker = true;
      if (field == "repair") {
        this.columns = [
          { name: "是", value: 1 },
          { name: "否", value: 2 }
        ];
      } else if (field == "outUser") {
        this.columns = [
          { name: "服务人员1", value: 1 },
          { name: "服务人员2", value: 2 }
        ];
      }
      this.field = field;
    },
    onConfirm(val, field) {
      let year = val.getFullYear();
      let month = val.getMonth() + 1;
      let day = val.getDate();
      let hour = val.getHours();
      let minute = val.getMinutes();
      // let second = val.getSeconds()
      if (month >= 1 && month <= 9) {
        month = `0${month}`;
      }
      if (day >= 1 && day <= 9) {
        day = `0${day}`;
      }
      if (hour >= 0 && hour <= 9) {
        hour = `0${hour}`;
      }
      if (minute >= 0 && minute <= 9) {
        minute = `0${minute}`;
      }
      // if (second >= 0 && second <= 9) { second = `0${second}` }
      this.dataSource[field] = `${year}-${month}-${day} ${hour}:${minute}:00`;
      this.showTimerPicker = false;
    },

    formatter(type, value) {
      if (type === "year") {
        return `${value}年`;
      } else if (type === "month") {
        return `${value}月`;
      } else if (type === "day") {
        return `${value}日`;
      } else if (type === "hour") {
        return `${value}时`;
      } else if (type === "minute") {
        return `${value}分`;
      } else if (type === "second") {
        return `${value}秒`;
      }
      return value;
    },
    //维修预约
    applyRepair() {
      this.$router.push("/applyRepair");
    },
    // 获取list名称
    getFieldName(list, key, val) {
      if (list && list.length > 0) {
        let obj = list.filter(item => {
          return item[key] == val;
        });
        if (obj.length > 0) {
          return obj[0].name;
        }
      }
      return null;
    },

    handleShowDo() {
      this.showShare = true;
    },
    onSelect(option) {
      console.log(option);
      let vm = this;
      // 单据状态 = 审核 且 出库状态= 未生成 且 是否配对=是 且 可出库=是 且 是否保险=是 且 可开票=是 且 （应付金额为空 或 应付金额 <=0）

      if (option.value == 1) {
        if (
          vm.dataSource.billStatus == "审核" &&
          vm.dataSource.stocked == "未生成" &&
          vm.dataSource.isAllcoated &&
          vm.dataSource.isCanout &&
          vm.dataSource.isInsur &&
          vm.dataSource.isCanInvoice &&
          (vm.dataSource.payAmount == null || vm.dataSource.payAmount <= 0)
        ) {
          Dialog.confirm({
            title: "提示",
            message: `确定对销售合同【${vm.dataSource.billNumber}】进行出库？`
          })
            .then(() => {
              // on confirm
              vm.saleContractGenOutStockByBOTP();
              console.log("删除");
            })
            .catch(() => {
              console.log("取消");
              // on cancel
            });
        } else {
          Notify({ type: "danger", message: "当前状态不满足出库条件" });
          return;
        }
      }

      this.showShare = false;
    },

    // 生成销售出库
    saleContractGenOutStockByBOTP() {
      sellManageApi
        .secondHandCarFacade({
          method: "saleContractGenOutStockByBOTP", //固定值
          saleContractId: this.detailId
        })
        .then(res => {
          if (res.code == 1) {
            Notify({ type: "success", message: "生成销售出库单成功" });
            this.getDetail(this.detailId);
          }
        });
    },

    handleFile() {
      this.$router.push({
        path: "/fileMange",
        query: { billId: this.dataSource.billId }
      });
    },
    editApply() {
      this.auditVisible = true;
    }
  }
};
</script>

<style lang="less" scoped>
body {
  background: #f3f3f3;
}
.flex {
  display: flex;
  align-items: center;
}
.van-swipe-item {
  width: 100%;

  img {
    width: 100%;
    display: block;
  }
}
.registerDetail {
  padding-bottom: 75px;
  .top_detail {
    display: flex;
    align-items: center;
    // width: 100%;
    background: #fff;
    padding: 10px;
    margin: 10px;
    .top_detail_lt {
      display: inline-block;
      text-align: center;
      width: 50%;
      border-right: 1px solid #f0f0f0;
    }
    .top_detail_rt {
      width: 50%;
      display: inline-block;
      text-align: center;
    }
    .top_name {
      font-weight: bold;
      font-size: 16px;
      margin-bottom: 5px;
    }
    .top_status {
      color: red;
      font-size: 16px;
      margin-bottom: 5px;
    }
    .top_txt {
      font-size: 16px;
      color: #333;
      margin-bottom: 5px;
      .icon-tel {
        background: #35bc04;
        color: #fff;
        border-radius: 50%;
        padding: 5px;
      }
    }
  }
}
.headerbox {
  width: 100%;
  overflow-x: auto;
  &::-webkit-scrollbar {
    display: none;
  }
}
.header_top {
  display: flex;
  align-self: center;
  padding: 10px;
  overflow-x: auto;
  // width: 12rem;
  .header_item {
    // width: 3rem;
    background: #fff;
    padding: 10px 15px;
    font-size: 16px;
    border-radius: 5px;
    margin-right: 10px;
    .txt {
      margin-bottom: 5px;
    }
    &.active {
      border: 1px solid #ccc;
      box-shadow: 1px 1px 3px rgba(0, 0, 0, 0.3);
    }
  }
}
.buy_content {
  .buy_name {
    background: #fff;
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 15px;
    padding-top: 5px;
  }
  .carInfo {
    padding: 10px;
    background: #fff;
    margin-bottom: 10px;
    .source {
      padding-left: 0 !important;
      margin-bottom: 10px;
      justify-content: space-between;

      .source_txt {
        font-size: 16px;
      }
    }

    .carInfo_No {
      margin-bottom: 15px;
      .carInfo_No_item {
        border-right: 1px solid #ccc;
        padding-right: 5px;
        margin-right: 5px;
        font-size: 16px;
        color: #333;
        &:last-child {
          border: none;
        }
      }
    }
    .carInfo_item {
      font-size: 16px;
      margin-bottom: 5px;
      color: #333;
      .carInfo_item_price {
        width: 50%;
      }
    }
    .carInfo_title {
      font-size: 16px;
      color: #333;
      margin-bottom: 10px;
      font-weight: bold;
    }
  }
}
.buy_footer {
  background: #fff;
  flex-wrap: wrap;
  box-sizing: border-box;
  width: 100%;
  .buy_footer_item {
    box-sizing: border-box;
    width: 50%;
    padding: 15px;
    justify-content: space-between;
    border-bottom: 1px solid #f5f5f5;
    border-right: 1px solid #f5f5f5;
    .buy_footer_lt {
      font-size: 16px;
      color: #333;
      padding-left: 15px;
      .txt {
        color: #bbbbbb;
        margin-top: 10px;
        font-size: 14px;
      }
    }
    .buy_footer_rt {
    }
  }
}

.morebox {
  position: fixed;
  bottom: 0;
  left: 0;
  z-index: 99;
  width: 100%;
  background: #fff;
  .moreBtn {
    background: #409eff;
    color: #fff;
    width: 75%;
    margin: auto;
    text-align: center;
    padding: 12px;
    border-radius: 5px;
    margin-top: 15px;
    font-size: 16px;
    margin-bottom: 25px;
  }
}
/deep/ .van-share-sheet__icon {
  width: 40px;
  height: 40px;
}
</style>
